﻿
package extremefx.modules.seaDragon {

	/**
	 * @author Marcelo Volmaro
	 */
	internal final class Spring {
		private var _currentValue:Number;
		private var _startValue:Number;
		private var _targetValue:Number;
		private var _currentTime:Number;
		private var _startTime:Number;
		private var _targetTime:Number;

		public function Spring(pInitialValue:Number) {
			_startValue = _targetValue = _currentValue = pInitialValue || 0;
			_startTime = _currentTime = _targetTime = new Date().getTime();
		}
		
		public function transform(pX:Number):Number {
			var s:Number = Config.springStiffness;
			return (1.0 - Math.exp( - pX * s)) / (1.0 - Math.exp( - s));
		}
		
		public function getCurrent():Number {
			return _currentValue;
		}
		
		public function getTarget():Number {
			return _targetValue;
		}
		
		public function resetTo(pTarget:Number):void {
			_startValue = _targetValue = pTarget;
			_startTime = _targetTime = _currentTime;
		}
		
		public function springTo(pTarget:Number):void {
			_startValue = _currentValue;
			_startTime = _currentTime;
			_targetValue = pTarget;
			_targetTime = _startTime + 1000 * Config.animationTime;
		}
		
		public function shiftBy(pDelta:Number):void {
			_startValue += pDelta;
			_targetValue += pDelta;
		}
		
		public function update():void {
			_currentTime = new Date().getTime();
			_currentValue = (_currentTime >= _targetTime) ? _targetValue : _startValue + (_targetValue - _startValue) * transform((_currentTime - _startTime) / (_targetTime - _startTime));
		}
	}
}
